package com.gitee.hifong45.config;

import javax.annotation.Resource;

import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.gitee.hifong45.Prj;
import com.gitee.hifong45.Ret;
import com.gitee.hifong45.Str;
import com.gitee.hifong45.sub.ProjectInfo;

import cn.hutool.core.date.SystemClock;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import lombok.var;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/ext")
public class ExtController {

  @GetMapping("/prjinfo")
  public Ret<Object> getProjectInfo() {
    ProjectInfo info = Prj.getProjectInfo();
    return Ret.Ok(info);
  }

  @Resource
  LoggingSystem loggingSystem;
  /**
     * 
     * @param clz 需要设置的级别的记录器的全名称
     * @param level 级别 DEBUG/INFO/WARN/ERROR
     * @return 返回信息
     */
    @RequestMapping("/level")
    public String changeLevel(String clz, @RequestParam LogLevel level) {
        clz = Str.orElse(clz, "cn.dhldev.demo1.TestController");
        var str = StrUtil.format("change {} to {} success", clz, level);
        log.info(str);
        loggingSystem.setLogLevel("cn.dhldev.demo1.TestController", level); //resolveLogLevel(level));
        
        return str;
    }

    @RequestMapping(value = "/loglevel")
    public Ret<?> logLevel(String clz, String rw, String level) {
        clz = StrUtil.emptyToDefault(clz, this.getClass().getName());
        rw = StrUtil.emptyToDefault(rw, "READ");
        log.info("logLevel: clz={}, rw={}, level={}", clz, rw, level);
        String url = "http://127.0.0.1:12346/onlydev/loggers/" + clz;
        Dict ret = Dict.of("clz", clz);
        String resp = "";
        if(rw.equalsIgnoreCase("WRITE")) {
            level = StrUtil.emptyToDefault(level, "info");
            String param = StrUtil.format("{\"configuredLevel\":\"{}\"}", level);
            log.info("post {}, param= {}" , url, param);
            resp = HttpUtil.post(url, param);
        } 
        log.info("get {}, resp= {}", url, resp);
        resp = HttpUtil.get(url);
        
        ret.put("resp", resp);
        log.info("ret = {}", ret);
        return Ret.Ok(ret);
    }

}
